<?php

namespace app\index\model;

use frame\lib\Db;

class Index
{
    public static function main()
    {
        $user = Db::name('user')->where(['id' => $_SESSION['user']['id']])->find();
        $expirationDate = getTime(3, $user['vip_time']) < time() ? '<span class="layui-font-red">已到期，请即使续费</span> &nbsp;&nbsp<span class="layui-font-blue">只有会员才能看到数据哦 !</span>' : $user['vip_time'];
        // 用户数量
        $user = User::list();
        $statistics = self::statistics($user);
        // 卡密数量
        $fake = Fake::list();
        // 今日注册
        $todayReg = $statistics['todayReg'];
        // vip用户数量
        $vipUser = $statistics['vipUser'];
        // 今日访问量
        $statist = self::initStatist();
        $heat = $statist['heat'];
        $log = $statist['log'];
        if ($statist['today'] != date('d')) {
            Db::name('statistics')->where(['user_id' => $_SESSION['user']['id']])->update(['today' => date('d'), 'log' => 0, 'heat' => 0]);
            $heat = 0;
            $log = 0;
        }
        $data = ['userTotal' => count($user), 'fakeTotal' => count($fake), 'ip' => ip(), 'heat' => $heat, 'todayReg' => $todayReg, 'vipUser' => $vipUser, 'log' => $log, 'date' => $expirationDate];
        return $data;
    }

    public static function statistics($list)
    {
        // 今日注册
        $n = 0;
        // 会员数量
        $m = 0;
        foreach ($list as $k => $v) {
            if (date('d', getTime(3, $v['create_time'])) == date('d', time())) {
                $n++;
            }
            if (getTime(3, $v['vip_time']) > time()) {
                $m++;
            }
        }
        return ['todayReg' => $n, 'vipUser' => $m];
    }
    // 统计表初始化
    public static function initStatist()
    {
        $uid =  $_SESSION['user']['id'];
        $res = Db::name('statistics')->where(['user_id' => $uid])->find();
        if (!$res) {
            Db::name('statistics')->insert(['user_id' => $uid]);
        }
        $res = Db::name('statistics')->where(['user_id' => $uid])->find();
        return $res;
    }
}
